<?php

namespace App\Admin\Forms;

use Dcat\Admin\Widgets\Form;
use App\Models\VideoCategory;
use App\Models\Video;
use Illuminate\Support\Facades\DB;

class VideoBatchSettingForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $state = $input['state'] ??0;
        $is_recommend = $input['is_recommend'] ?? 0;
        $category_id = $input['category_id']??null;
        // id转化为数组
        $ids = explode(',', $input['ids'] ?? null);

        try{
            DB::beginTransaction();
            //过滤掉null
            $data = array_filter([
                'state'=>$state,
                'is_recommend'=>$is_recommend,
                'category_id'=>$category_id
            ],function($item){
                if($item === '' || $item === null){
                    return false;
                }
                return true;
            });
            //遍历
            foreach ($ids as $id) {
                Video::where('id',$id)->update([
                    'state'=>$state,
                    'is_recommend'=>$is_recommend,
                    'category_id'=>$category_id
                ]);
            }
            DB::commit();
        }catch(\Exception $e){
            \Log::error($e->getMessage());
            DB::rollBack();
            return $this->response()->alert(true)->error('操作失败，请重试');
        }
        return $this->response()->success('操作成功')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->select('category_id','视频分类')->options(VideoCategory::show()->pluck('name','id'));
        $this->switch('state','是否显示')->default(1);
        $this->switch('is_recommend','是否推荐');
        // 设置隐藏表单，传递用户id
        $this->hidden('ids')->attribute('id', 'setting-id');
    }
}
